<template>
    <div style="padding:0 10px">
        <div class="header">
            <!-- <query-condition
                @comReturn="comReturn"
                @handleButton="handleButton"
                :showSearchParams="showSearchParams"
                :isFirst="isFirst && activeValue === 'limit-balance'"
            ></query-condition> -->
            <limit-balance-query-condition @comReturn="comReturn" @handleButton="handleButton" :isFirst="isFirst && activeValue === 'limit-balance'">
            </limit-balance-query-condition>
        </div>
        <div :class="{ isOpened: isOpen, noOpened: !isOpen }">
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                v-table-top="page.currentPage"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                highlight-current-row
                @sort-change="changeTableSort"
                :resizable-config="{ minWidth: '60' }"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
            >
                <vxe-column
                    v-for="item in showFieldList"
                    :title="item.content"
                    :key="item.content"
                    :field="item.id"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '105px'"
                    :sortable="item.sortable"
                    show-overflow="tooltip"
                >
                    <template slot-scope="scope">
                        <span v-if="item.id == 'rsendDate'">
                            {{ dateFormat(scope.row[item.id]) || '--' }}
                        </span>
                        <span v-else-if="item.id == 'rsendDay'">
                            {{ thousandsFormat(scope.row[item.id]) || '--' }}
                        </span>
                        <span v-else-if="['restricedAmount', 'restricedBalance'].includes(item.id)">
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>
                        <span v-else-if="'restrictedType' == item.id">
                            {{ restrictedTypes[scope.row[item.id]] }}
                        </span>
                        <span v-else>
                            {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>

            <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>
        </div>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_LIMIT_BALANCE"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat, thousandsFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import LimitBalanceQueryCondition from './limit-balance-query-condition.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({ name: 'LimitBalance', components: { LimitBalanceQueryCondition, RiskTableLayout, RiskPagination } })
export default class LimitBalance extends Vue {
    dateFormat = dateFormat;
    numberFormat = numberFormat;
    thousandsFormat = thousandsFormat;

    @Prop() activeValue: string;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'limit-balance') {
            if (this.isFirst) {
                await this.queryLayout();
                this.getLimitBalanceTableData();
                this.isFirst = false;
            }
        }
    }

    isOpen: boolean = false;

    showSearchParams: any = ['fundCode', 'fundId', 'assetUnitCode', 'groupCode', 'stockCode', 'restrictedType', 'lockrestrictedType'];

    tableData: any[] = [];

    summary: any = {}; // 合并行

    // 受限资产类型
    restrictedTypes: any = {
        '1': '存款',
        '2': '融券回购',
        '3': '停牌股票',
        '4': '流通受限新股',
        '5': '非公开发行股票',
        '6': '未上市股票',
        '7': '违约债券',
        '8': '资产支持证券',
        '9': '封闭基金',
        '10': '定开基金',
    };
    sortableObj = {
        // fundCode: 'VC_FUND_CODE',

        fundId: 'L_FUND_ID',

        fundName: 'VC_FUND_NAME',

        // unitId: 'L_UNIT_ID ',

        assetId: 'L_ASSET_ID',

        assetName: 'VC_ASSET_NAME',

        basecombiId: 'L_BASECOMBI_ID',

        combiName: 'VC_COMBI_NAME',

        stockCode: 'VC_INTER_CODE',

        stockNameSt: 'VC_STOCK_NAME',

        restrictedType: 'C_RESTRICTED_TYPE',

        lockrestrictedType: 'C_LOCKRESTRICTED_TYPE',

        rsendDate: 'L_RSEND_DATE',

        restricedAmount: 'L_RESTRICTED_AMOUNT',

        stockType: 'C_STOCK_TYPE',
        assetClass: 'C_ASSET_CLASS_CODE',
        investType: 'C_INVEST_TYPE_CODE',
        // liquidityDiscountNumber: 'liquidityDiscountNumber',
        // price: 'price',
        restricedBalance: 'C_RESTRICTED_BALANCE',
        marketName: 'VC_MARKET_NAME',
        rsendDay: 'L_RSEND_DAY',
    };

    tableColumns = [
        {
            content: '产品序号',
            id: 'fundId',
            align: 'left',
            sortable: true,
        },
        // {
        //     content: '产品编码',
        //     id: 'fundCode',
        // },
        {
            content: '产品名称',
            id: 'fundName',
            align: 'left',
            sortable: true,
        },
        // {
        //     content: '投资单元序号',
        //     id: 'unitId',
        //     minWidth: '130px',
        // },
        {
            content: '资产单元编号',
            id: 'assetId',
            minWidth: '130px',
            align: 'left',
            sortable: true,
        },
        {
            content: '资产单元名称',
            id: 'assetName',
            minWidth: '130px',
            align: 'left',
            sortable: true,
        },
        {
            content: '组合编码',
            id: 'basecombiId',
            align: 'left',
            sortable: true,
        },
        {
            content: '组合名称',
            id: 'combiName',
            align: 'left',
            sortable: true,
        },
        {
            content: '证券代码',
            id: 'stockCode',
            align: 'left',
            sortable: true,
        },
        {
            content: '证券名称',
            id: 'stockNameSt',
            align: 'left',
            sortable: true,
        },

        { id: 'stockType', content: '证券类别', sortable: true, align: 'center' },
        { id: 'assetClass', content: '资产分类', sortable: true, align: 'center' },
        { id: 'investType', content: '投资类型', sortable: true, align: 'center' },
        {
            content: '交易市场',
            id: 'marketName',
            align: 'center',
            sortable: true,
        },
        {
            content: '受限资产类型', // 受限类型
            id: 'restrictedType',
            minWidth: '120px',
            align: 'center',
            sortable: true,
        },
        // {
        //     content: '锁定受限类型',
        //     id: 'lockrestrictedType',
        //     minWidth: '140px',
        // },
        {
            content: '受限结束日期',
            id: 'rsendDate',
            minWidth: '130px',
            align: 'center',
            sortable: false,
        },
        {
            content: '剩余受限天数',
            id: 'rsendDay',
            minWidth: '130px',
            sortable: false,
        },
        {
            content: '受限持仓数量',
            id: 'restricedAmount',
            sortable: true,
        },
        // { id: 'liquidityDiscountNumber', content: '流动性折扣系数', minWidth: '150px' },
        // { id: 'price', content: '价格' },
        { id: 'restricedBalance', content: '受限持仓市值', minWidth: '130px', sortable: true },
    ];

    private page: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    private sortProp: string = 'fundId'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_FUND_ID ASC'; // 默认排序字段

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { id: 'fundId', content: '产品序号', sortable: true, align: 'left' },
        // { id: 'fundCode', content: '产品编码' },
    ];

    searchParam: any = {
        assetUnitCode: '',
        categoryCode: '',
        fundId: '',
        groupCode: '',
        investType: '',
        marketCode: '',
        restrictedType: '',
        stockCode: '',
    }; // 查询条件

    loading: boolean = false; // 页面渲染

    tableKey: number = -1;

    isFirst: boolean = true;

    getLimitBalanceTableData(): void {
        this.loading = true;
        this.$axios
            .post('/assetSelect/floatLimitAsset', {
                ...this.searchParam,
                stockCode: this.searchParam.stockCode && this.searchParam.stockCode.toString().replace(' ', ''),
                sort: this.sort,
                paging: {
                    currentPage: this.page.currentPage,
                    pageSize: this.page.pageSize,
                },
            })
            .then((res: any) => {
                if (res.total) {
                    this.summary = res.list[res.list.length - 1];
                    this.tableData = res.list.slice(0, res.list.length - 1);
                } else {
                    this.summary = {};
                    this.tableData = [];
                }
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 查询返回
    comReturn(obj) {
        this.isOpen = obj.isOpen;
        this.searchParam = obj.searchParam;
    }

    pageRet() {
        this.getLimitBalanceTableData();
    }

    // 分页
    pageChange(curPage: number): void {
        this.page.currentPage = curPage;
        this.getLimitBalanceTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_LIMIT_BALANCE')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            this.showFieldList = this.tableColumns;
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
            } else {
                this.showFieldList = this.fixedFieldList.concat(JSON.parse(resList));
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }
        const fixKeys = this.fixedFieldList.map(item => item.id);
        this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        this.tableKey++;
    }

    // beforeUpdate() {
    //     this.$nextTick(() => {
    //         // 在数据加载完，重新渲染表格
    //         (this.$refs['table'] as any).doLayout();
    //     });
    // }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let obj = this.tableData[0];
            let objR = this.summary;

            for (let item of this.showFieldList) {
                // if (objR[item.id] && ['restricedAmount', 'restricedBalance'].includes(item.id)) {
                if (['restricedAmount', 'restricedBalance'].includes(item.id) && objR) {
                    // if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2) || '--';
                } else {
                    arr[count++] = '--';
                }
            }
            console.log([arr]);
        }
        return [arr];
    }

    // 按钮点击
    handleButton(type): void {
        if (type == 'search') {
            this.pageChange(1);
        } else if (type == 'refresh') {
            this.pageChange(1);
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        }
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';
.isOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 350px);
    }
}
</style>
